<?
function drizzo_user_info($id = null, $var = 'all') {
	drizzo_db_connect();
	global $drizzo_users;
	
	if($var == 'display_name') {
		$display_name = drizzo_user_options($id, 'display_name');
		$result = @mysql_query("SELECT `nice_name`,`first_name`,`last_name`,`username` FROM `$drizzo_users` WHERE `ID`='$id'");
		if(!mysql_errno()) {
			while($user = mysql_fetch_assoc($result)) {
				foreach($user as $field => $value) {
					$user_meta[$field] = $value;
				}
			}
			if($var == 'nicename' && !empty($user_meta['nice_name'])) {
				return $user_meta['nice_name'];
			} elseif($var == 'firstname' && !empty($user_meta['first_name'])) {
				return $user_meta['first_name'];
			} elseif($var == 'firstname_lastname' && !empty($user_meta['first_name']) && !empty($user_meta['last_name'])) {
				return $user_meta['first_name'] . " " . $user_meta['last_name'];
			} elseif($var == 'lastname_firstname' && !empty($user_meta['first_name']) && !empty($user_meta['last_name'])) {
				return $user_meta['last_name'] . ", " . $user_meta['first_name'];
			} else {
				return $user_meta['username'];
			}
		} else {
			return false;
		}
	}

	if($id) {
		if($var == 'all') {
			$result = @mysql_query("SELECT * FROM `$drizzo_users` WHERE `ID`='$id'");
			if(!mysql_errno()) {
				while($user = mysql_fetch_assoc($result)) {
					foreach($user as $field => $value) {
						$user_meta[$field] = $value;
					}
				}
				$display_name = drizzo_user_options($id, 'display_name');
				if($display_name == 'nicename' && !empty($user_meta['nice_name'])) {
					$user_meta['display_name'] = $user_meta['nice_name'];
				} elseif($display_name == 'firstname' && !empty($user_meta['first_name'])) {
					$user_meta['display_name'] = $user_meta['first_name'];
				} elseif($display_name == 'firstname_lastname' && !empty($user_meta['first_name']) && !empty($user_meta['last_name'])) {
					$user_meta['display_name'] = $user_meta['first_name'] . " " . $user_meta['last_name'];
				} elseif($display_name == 'lastname_firstname' && !empty($user_meta['first_name']) && !empty($user_meta['last_name'])) {
					$user_meta['display_name'] = $user_meta['last_name'] . ", " . $user_meta['first_name'];
				} else {
					$user_meta['display_name'] = $user_meta['username'];
				}
				return $user_meta;
			} else {
				return false;
			}
		} else {
			$result = @mysql_query("SELECT `$var`,`username` FROM `$drizzo_users` WHERE `ID`='$id'");
			if(@mysql_num_rows($result) > 0) {
				while($field = @mysql_fetch_assoc($result)) {
					if(substr_count($var,"name") > 0 && empty($field[$var])) {
						return $field['username'];
					} else {
						return $field[$var];
					}
				}
			} else {
				return false;
			}
		}
	} else {
		drizzo_db_connect();

		global $drizzo_users;

		$session_user_enc = $_COOKIE['drizzo_user'];
		$result = @mysql_query("SELECT `ID`,`user_level`,`username` FROM `$drizzo_users` WHERE `username_md5`='$session_user_enc'");
		if(!mysql_errno()) {
			while ($row = @mysql_fetch_assoc($result)) {
				define("session_user_id", $row['ID']);
				define("session_user_level", $row['user_level']);
				define("session_username", $row['username']);
				return true;
			}
		} else {
			return false;
		}
	}
}

function drizzo_user_has_avatar($id = null) {
	if(!$id) {
		global $the_post;
		$id = $the_post['author'];
	}
	return drizzo_user_info($id, 'avatar');
}

function drizzo_get_the_users($user_level = 'all') {
	global $drizzo_users;
	if($user_level == 'all') {
		$users_lookup = @mysql_query("SELECT * FROM `$drizzo_users` ORDER BY `nice_name`");
		if(!mysql_errno()) {
			while($row = @mysql_fetch_assoc($users_lookup)) {
				if($row['nice_name'] == null) {
					$row['nice_name'] = $row['username'];
				}
				$users[] = $row;
			}
			return $users;
		} else {
			return false;
		}
	} else {
		$users_lookup = @mysql_query("SELECT * FROM `$drizzo_users` WHERE `user_level`='$user_level' ORDER BY `nice_name`");
		if(!mysql_errno()) {
			while($row = @mysql_fetch_assoc($users_lookup)) {
				if($row['nice_name'] == null) {
					$row['nice_name'] = $row['username'];
				}
				$users[] = $row;
			}
			return $users;
		} else {
			return false;
		}
	}
}

function drizzo_user_posts($id) {
	global $drizzo_posts;
	$post_lookup = @mysql_query("SELECT `ID` FROM `$drizzo_posts` WHERE `author`='$id'");
	if(@mysql_num_rows($post_lookup) > 0) {
		return @mysql_num_rows($post_lookup);
	} else {
		return "0";
	}
}

function drizzo_user_is_allowed($task = null) {
	if($task) {
		$user_level = session_user_level;
		if($user_level == 5) { // Admins can do it all
			$allow = true;
		} elseif($user_level == 4) { // Editors cannot change site options or make changes to plugins but can do everything else
			$allowed = array('blog-write','blog-publish','pages-write','pages-publish','comments-publish','comments-moderate','podcasts-write','podcasts-publish','reviews-write','reviews-publish','events-write','events-publish','gallery-write','gallery-publish','media-publish','media-write','links-publish-global','links-publish-user','users-add','users-edit','users-promote','users-delete');
			if(array_search($task,$allowed)) {
				$allow = true;
			}
		} elseif($user_level == 3) { // Publishers can write, edit and publish their own posts; moderate comments; post podcasts and events; add links and media; and add new users
			$allowed = array('blog-write','blog-publish','pages-write','pages-publish','comments-publish','comments-moderate','podcasts-write','podcasts-publish','reviews-write','reviews-publish','events-write','events-publish','gallery-write','gallery-publish','media-publish','media-write','links-publish-user','users-add');
			if(array_search($task,$allowed)) {
				$allow = true;
			}
		} elseif($user_level == 2) { // Posters can write and edit their own posts, podcasts, events, and media but cannot publish them
			$allowed = array('blog-write','pages-write','comments-publish','podcasts-write','reviews-write','events-write','gallery-write','media-write');
			if(array_search($task,$allowed)) {
				$allow = true;
			}			
		} elseif($user_level == 1) { // Regulars can post comments and edit their own profile
			if($task == 'comments-publish') {
				$allow = true;
			}
		} else { // non-registered vistors can only write comments but they may be held in moderation
			$allow = false;
		}
	} else {
		$allow = false;
	}
	return $allow;
}

function drizzo_users_batch_update() {
	global $drizzo_users;
	
	if($_POST['batch_action'] && $_POST['batch_action'] != "") {
		if($_POST['batch_action'] == 'delete') {
			if($_POST['batch']) {
				foreach($_POST['batch'] as $id => $state) {
					$delete_query = @mysql_query("DELETE FROM `$drizzo_users` WHERE `ID`='$id'");
					if(!mysql_errno()) {
						$delete_count++;
					}
				}
			}
			if($delete_count == count($_POST['batch'])) {
				$response = "<p class=\"trash\">The selected users have been deleted.</p>";
			} elseif($delete_count < count($_POST['batch'])) {
				$response = "<p class=\"alert\">Some of the selected users have been deleted.</p>";
			} else {
				$response = "<p class=\"alert\">None of the selected users could be deleted.</p>";
			}
		} else {
			$new_level = $_POST['batch_action'];
			if($_POST['batch']) {
				foreach($_POST['batch'] as $id => $state) {
					if($state == 'on') {
						$update_query = @mysql_query("UPDATE `$drizzo_users` SET `user_level`='$new_level' WHERE `ID`='$id'");
						if(!mysql_errno()) {
							$update_count++;
						}
					}
				}
			}
			if($update_count == count($_POST['batch'])) {
				$response = "<p class=\"save\">The selected users have been updated.</p>";
			} elseif($update_count < count($_POST['batch'])) {
				$response = "<p class=\"alert\">Some of the selected users have been updated.</p>";
			} else {
				$response = "<p class=\"alert\">None of the selected users could be updated.</p>";
			}
		}
	} else {
		$response = false;
	}
	return $response;
}

function drizzo_user_update() {
	global $drizzo_users, $edit;
	if($_POST) {
		$response = null;
		$current_user_lookup = @mysql_query("SELECT `ID` FROM `$drizzo_users` WHERE `ID`='$edit'");
		if(@mysql_num_rows($current_user_lookup) > 0) {
			$user_exists = true;
		} else {
			$user_exists = false;
		}
		if(!$user_exists && $_POST['username']) {
			$username_lookup = @mysql_query("SELECT `ID` FROM `$drizzo_users` WHERE `username`='$_POST[username]'");
			if(@mysql_num_rows($username_lookup) > 0) {
				return "<p class=\"alert\">The username is already in use. Please go back and choose a different username.</p>\n";
			} else {
				$data = "`username`='$_POST[username]',`username_md5`='" . md5($_POST['username']) . "',`date_added`='" . time() . "',";
			}
		}
		extract($_POST);
		if(strlen($new_password) > 0 && $new_password != $new_password2) { // The new passwords don't match
			$response .= "<p class=\"alert\">The passwords did not match</p>\n";
			
		} elseif(strlen($new_password) > 0 && $new_password == $new_password2) { // The new passwords do match
			foreach($_POST as $field => $value) {
				if($value != null && $value != '' && $field != "MAX_FILE_SIZE") {
					if($field == 'new_password') {
						$data .= "`password`='" . md5($value) . "',";
					} elseif($field == 'new_password2' || $field == 'username' || $field == 'display_name') {
						// Do Nothing
					} else {
						$data .= "`$field`='" . drizzo_db_wrap($value) . "',";
					}
				}
			}
			$data = rtrim($data,",");
			if($user_exists) {
				$data .= ",`date_edited`='" . time() . "',`edited_by`='" . session_user_id . "'";
				$update_query = @mysql_query("UPDATE `$drizzo_users` SET $data WHERE `ID`='$edit'");
				if(!mysql_errno()) {
					$response .= "<p class=\"save\">The new password and updated data were saved</p>\n";
				} else {
					$response .= "<p class=\"alert\">The updated data could not be saved" . mysql_error() . "</p>";
				}
			} else {
				$update_query = @mysql_query("INSERT INTO `$drizzo_users` SET $data");
				if(mysql_insert_id() > 0) {
					$insert_id = mysql_insert_id();
					$response .= "<p class=\"save\">The new user was added</p>\n";
				} else {
					$response .= "<p class=\"alert\">The new user could not be added<br />" . mysql_error() . "</p>";
				}
			}
			if($_FILES['avatar']['size'] > 0) {
				if(array_search($_FILES['avatar']['type'],array('image/gif','image/jpeg','image/jpg','image/jpe','image/png'))) {
					$avatar_data = mysql_real_escape_string(fread(fopen($_FILES['avatar']['tmp_name'], "r"), filesize($_FILES['avatar']['tmp_name'])));
					$avatar_query = @mysql_query("UPDATE `$drizzo_users` SET `avatar`='$avatar_data' WHERE `ID`='$edit'");
					if(!mysql_errno()) {
						$response .= "<p class=\"save\">The new avatar was saved</p>\n";
					} else {
						$response .= "<p class=\"alert\">The new avatar could not be saved" . mysql_error() . "</p>\n";
					}
				} else {
					$response .= "<p class=\"alert\">The avatar image was of the wrong type. Only pngs, gifs, and jpgs are allowed.</p>\n";
				}
			}
		} else { // There is no new password
			if($_FILES['avatar']['size'] > 0) {
				if(array_search($_FILES['avatar']['type'],array('image/gif','image/jpeg','image/jpg','image/jpe','image/png'))) {
					$avatar_data = addslashes(fread(fopen($_FILES['avatar']['tmp_name'], "r"), filesize($_FILES['avatar']['tmp_name'])));
					if(!$user_exists) {
						$avatar_query = @mysql_query("UPDATE `$drizzo_users` SET `avatar`='$avatar_data' WHERE `ID`='$edit'");
					} else {
						$avatar_query = @mysql_query("INSERT INTO `$drizzo_users` SET `avatar` VALUES ('$avatar_data')");
					}
					if(@mysql_num_rows($avatar_query) > 0) {
						$response .= "<p class=\"save\">The new avatar was saved</p>\n";
					} else {
						$response .= "<p class=\"alert\">The new avatar could not be saved" . mysql_error() . "</p>\n";
					}
				} else {
					$response .= "<p class=\"alert\">The avatar image was of the wrong type. Only pngs, gifs, and jpgs are allowed.</p>\n";
				}
			}
			foreach($_POST as $field => $value) {
				if($value != null && $value != '') {
					if($field == 'new_password' || $field == 'new_password2' || $field == "MAX_FILE_SIZE" || $field == 'display_name') {
						// Do Nothing
					} else {
						$data .= "`$field`='" . drizzo_db_wrap($value) . "',";
					}
				}
			}
			$data = rtrim($data,",");
			if($user_exists) {
				$data .= ",`date_edited`='" . time() . "',`edited_by`='" . session_user_id . "'";
				$update_query = @mysql_query("UPDATE `$drizzo_users` SET $data WHERE `ID`='$edit'");
				if(!mysql_errno()) {
					$response .= "<p class=\"save\">The updated data was saved</p>\n";
				} else {
					$response .= "<p class=\"alert\">The updated data could not be saved" . mysql_error() . "</p>";
				}
			} else {
				$response .= "<p class=\"alert\">The new user could not be added because no password was specified</p>\n";
			}
		}
		if(isset($_POST['display_name'])) {
			if($insert_id > 0) {
				drizzo_update_user_options('display_name',$_POST['display_name'],$insert_id);
			} elseif($edit) {
				drizzo_update_user_options('display_name',$_POST['display_name'],$edit);
			}
		}
	} else {
		$response =  false;
	}
	return $response;
}
?>
